<template>
  <div class="app-container">
    <div id="map"></div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="归属区域">
        <el-input v-model="queryParams.regionName" placeholder="请输入归属区域" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="归属门店">
        <el-input v-model="queryParams.storeName" placeholder="请输入归属门店" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户姓名" prop="userName">
        <!-- <el-select
          clearable
          v-model="queryParams.userName"
          filterable
          @change="changeuserName"
        >
          <el-option
            v-for="(item, index) of userName"
            :key="index"
            :label="item.value"
            :value="item.value"
            >{{ item.value }}</el-option
          >
        </el-select> -->
        <el-input v-model="queryParams.userName" placeholder="请输入客户姓名" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input v-model="queryParams.phoneNumber" placeholder="请输入联系电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          v-hasPermi="['business:memCard:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:memCard:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:memCard:del']">批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-setting" size="mini" :disabled="multiple" @click="handleGive"
          v-hasPermi="['business:memCard:give']">赠送优惠券</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:memCard:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" max-height="650px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="序号" align="center" prop="id" /> -->
      <el-table-column label="归属区域" align="center" prop="regionName" :show-overflow-tooltip="true" />
      <el-table-column label="归属门店" align="center" prop="storeName" :show-overflow-tooltip="true" />

      <el-table-column label="客户姓名" align="center" prop="userName" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <span>{{
            scope.row.gender == 0 ? "男" : scope.row.gender == 1 ? "女" : "未知"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="phoneNumber" />
      <el-table-column label="生日" align="center" prop="dateOfBirth" />

      <el-table-column label="消费频次" align="center" prop="consumeFrequencyState" />
      <!-- <el-table-column label="会员卡编号" align="center" prop="id" width="150" /> -->

      <el-table-column label="会员卡名称" align="center" prop="ruleName" width="150" />

      <el-table-column label="适用门店" align="center" prop="stores" :show-overflow-tooltip="true" />

      <el-table-column label="折扣" align="center" prop="discountRate" />

      <el-table-column label="优惠券名称" :show-overflow-tooltip="true"  align="center" prop="couponName" />
      <el-table-column label="优惠券数量" align="center" prop="couponNumber" />
      <el-table-column label="实付金额" align="center" prop="actuallyMoney" />
      
      <el-table-column label="支付方式" align="center" prop="paymentType">
        <template slot-scope="scoped">
          <div>
            {{
              (moneyConfig[scoped.row.paymentType] || moneyConfig["default"])
                .text
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="提成技师" align="center" prop="referrerName" />

      <el-table-column label="购买价格" align="center" prop="price" />
      <el-table-column label="会员开始时间" align="center" prop="createTime" />
      <el-table-column label="会员结束时间" align="center" prop="endTime" />

      <el-table-column label="剩余有效期" align="center" prop="validDays" />
      <el-table-column label="状态" align="center" prop="cardStatus" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.cardStatus == 1 ? "启用" : "禁用" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="创建者" align="center" prop="createBy" />

      <el-table-column label="修改时间" align="center" prop="updateTime" />
      <el-table-column label="修改者" align="center" prop="updateBy" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="queryConsumptionList(scope.row)"
            v-hasPermi="['business:memCard:calendar']">消费记录</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:memCard:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-upload2" @click="handleGround(scope.row, (cardStatus = 1))"
            v-hasPermi="['business:memCard:open']" :disabled="scope.row.cardStatus === 1">启用</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleGround(scope.row, (cardStatus = 0))"
            v-hasPermi="['business:memCard:disabled']" :disabled="scope.row.cardStatus === 0">禁用</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleRenew(scope.row)"
            v-hasPermi="['business:memCard:renew']">续费</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:memCard:del']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改门店对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false"
      @close="closeCommonVisible">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="会员卡编号" prop="id" v-if="title == '会员卡续卡'">
              <el-input :disabled="title == '会员卡续卡' || title == '修改会员卡'" v-model="form.id" placeholder="请输入会员卡编号"
                style="width: 222px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime" v-if="title == '会员卡续卡'">
              <el-input :disabled="title == '会员卡续卡' || title == '修改会员卡'" v-model="form.createTime" placeholder="请输入创建时间"
                style="width: 222px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属区域" prop="regionId">
              <el-select clearable v-model="form.regionId" @change="changeRegion"
                :disabled="title == '会员卡续卡' || title == '修改会员卡'">
                <el-option v-for="(item, index) of region" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属门店" prop="storeId">
              <el-select v-model="form.storeId" clearable @change="changeStore"
                :disabled="title == '会员卡续卡' || title == '修改会员卡'">
                <el-option v-for="(item, index) of store" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户电话" prop="phoneNumber">
              <el-select clearable v-model="form.phoneNumber" filterable allow-create @change="changephoneNumber"
                :disabled="title == '会员卡续卡' || title == '修改会员卡'" @blur="blurphoneNumber">
                <el-option v-for="(item, index) of userName" :key="index" :label="item.value" :value="item.key">{{
                  item.value }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入客户姓名" :disabled="title == '会员卡续卡' || title == '修改会员卡'"
                style="width: 222px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select clearable v-model="form.gender" :disabled="title == '会员卡续卡' || title == '修改会员卡'">
                <el-option v-for="(item, index) of gender" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="生日">
              <el-date-picker clearable v-model="form.dateOfBirth" :disabled="title == '会员卡续卡' || title == '修改会员卡'"
                type="date" style="width: 222px" value-format="yyyy-MM-dd" placeholder="请选择出生年月">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="title != '会员卡续卡'">
            <el-form-item label="推荐人" prop="referrerId">
              <el-select clearable v-model="form.referrerId" filterable @change="changeReferrer">
                <el-option v-for="(item, index) of jishi" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="title == '会员卡续卡'">
            <el-form-item label="原会员卡" prop="originRuleName">
              <el-input v-model="form.originRuleName" style="width: 222px" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="title == '会员卡续卡'">
            <el-form-item label="剩余天数" prop="days">
              <el-input v-model="form.validDays" disabled placeholder="0" style="width: 222px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员卡" prop="ruleId">
              <el-select clearable v-model="form.ruleId" @change="changeRule">
                <el-option v-for="(item, index) of Rule" :key="index" :label="item.value" :disabled="item.disabled"
                  :value="item.key">{{ item.value }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="title == '添加会员卡'">
            <el-form-item label="价格">
              <el-input v-model="memberPrice" disabled placeholder="" style="width: 222px" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="title == '添加会员卡'">
            <el-form-item label="天数">
              <el-input v-model="memberDays" disabled placeholder="" style="width: 222px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实付金额" prop="actuallyMoney" v-if="title == '添加会员卡'">
              <!-- @input="
                (value) =>
                  (this.form.actuallyMoney = value.replace(/[^\d]/g, ''))
              " -->
              <el-input v-model="form.actuallyMoney" placeholder="请输入实付金额" style="width: 222px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="天数" prop="days" v-if="title == '会员卡续卡'">
              <el-input v-model="form.days" disabled placeholder="请输入天数" style="width: 222px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="title == '会员卡续卡'">
            <el-form-item label="原价" prop="buyMoney">
              <el-input v-model="form.buyMoney" placeholder="" disabled style="width: 222px" />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="title == '会员卡续卡'">
            <el-form-item label="剩余天数抵扣价格" prop="dayDiscountPrice">
              <el-input v-model="form.dayDiscountPrice" disabled placeholder="" style="width: 222px" :key="isInput" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="title == '会员卡续卡'">
            <el-form-item label="推荐人" prop="referrerId">
              <el-select clearable v-model="form.referrerId" filterable @change="changeReferrer">
                <el-option v-for="(item, index) of jishi" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="title == '会员卡续卡'">
            <el-form-item label="最终支付价格" prop="price">
              <el-input disabled v-model="form.price" placeholder="" style="width: 222px" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentType">
              <el-select clearable v-model="form.paymentType" :disabled="disabled" @change="paymentTypeChange">
                <el-option v-for="(item, index) of money" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- :rules="[{ required: true, message: '请输入支付码', trigger: 'blur' }]" -->
          <el-col :span="12">
            <el-form-item label="条形码" prop="payCode" v-if="form.paymentType == 7 && title != '修改会员卡'"
              >
              <el-input v-model="form.payCode" placeholder="请输入条形码" @change="handleScanCode" ref="barcode"
                style="width: 222px"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" v-else>
            <el-form-item label="条形码" prop="payCode" v-if="form.paymentType == 7"
              :rules="[{ required: true, message: '请输入支付码', trigger: 'blur' }]">
              <el-input v-model="form.payCode" placeholder="请输入条形码" @change="handleScanCode" ref="barcode"
                style="width: 222px"></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row v-if="isGroupBuy">
          <el-col :span="12">
            <el-form-item label="团购劵" prop="groupPurchaseId">
              <el-input v-model="form.groupPurchaseId" :disabled="disabled" placeholder="请输入团购券码"
                style="width: 222px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实付金额" prop="groupPurchaseMoney">
              <el-input @input="
                (value) =>
                  (this.form.groupPurchaseMoney = value.replace(/[^\d]/g, ''))
              " v-model="form.groupPurchaseMoney" :disabled="disabled" placeholder="请输入实付金额" style="width: 222px" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            <el-input
              v-model="form.payCode"
              placeholder="请输入内容"
              @change="handleScanCode"
              ref="code"
              style="opacity: 0"
            ></el-input>
          </el-col>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 赠送优惠券弹框 -->
    <el-dialog :title="title" :visible.sync="giveDialog" width="1150px" append-to-body :close-on-click-modal="false">
      <el-table v-loading="loading" :data="couponList" @selection-change="handleGiveChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="序号" align="center" prop="storeName" /> -->
        <el-table-column label="优惠券名称" align="center" prop="name" width="120" />
        <el-table-column label="优惠券类型" align="center" prop="discountsType" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.discountsType == 1 ? '折扣券' : '立减券' }}</span>
          </template>
       </el-table-column>
        <el-table-column label="归属区域" align="center" prop="regionName" width="120">
          <template slot-scope="scope">
            <el-tooltip class="tooltip" placement="top">
              <div slot="content" style="max-width: 650px">
                {{
                  scope.row.regionName === null ? "无" : scope.row.regionName
                }}
              </div>
              <p class="descStyle">
                {{
                  scope.row.regionName === null ? "无" : scope.row.regionName
                }}
              </p>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="归属门店" align="center" prop="storeName">
          <template slot-scope="scope">
            <el-tooltip class="tooltip" placement="top">
              <div slot="content" style="max-width: 650px">
                {{ scope.row.storeName === null ? "无" : scope.row.storeName }}
              </div>
              <p class="descStyle">
                {{ scope.row.storeName === null ? "无" : scope.row.storeName }}
              </p>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="优惠券图片"
          align="center"
          prop="picture"
          width="160"
        >
          <template slot-scope="scope">
            <image-preview :src="scope.row.picture" :width="50" :height="50" />
          </template>
        </el-table-column> -->
        <el-table-column label="优惠门槛" align="center" prop="fullAmount" width="120" />
        <el-table-column label="优惠金额" align="center" prop="discountAmount" width="120">
          <template slot-scope="scope">
            <span>{{
              scope.row.discountAmount ? scope.row.discountAmount : "暂无"
            }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="适用项目" align="center" prop="projectName"  width="120"/> -->
        <el-table-column label="适用项目" align="center" prop="projectName">
          <template slot-scope="scope">
            <el-tooltip class="tooltip" placement="top">
              <div slot="content" style="max-width: 650px">
                {{
                  scope.row.projectName === null ? "无" : scope.row.projectName
                }}
              </div>
              <p class="descStyle">
                {{
                  scope.row.projectName === null ? "无" : scope.row.projectName
                }}
              </p>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="使用周期" align="center" prop="useToday" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.useToday ? scope.row.useToday : "暂无" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上架" align="center" prop="state" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.state == "1" ? "上架" : "下架" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      </el-table>
      <pagination v-show="total1 > 0" :total="total1" :page.sync="pageNum" :limit.sync="pageSize"
        @pagination="getCouponList" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="couponSubmit">确 定</el-button>
        <el-button @click="couponCancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="消费记录" :visible.sync="isConsumCludes" width="750px" append-to-body :close-on-click-modal="false">
      <el-table v-loading="loading" :data="consumCludes" max-height="600px">
        <el-table-column label="订单号" align="center" prop="orderId" width="160" />
        <el-table-column label="消费门店" align="center" prop="storeString" />
        <el-table-column label="消费项目" align="center" prop="itemName" width="150" />
        <el-table-column label="消费金额(元)" align="center" prop="paymentMoney" width="120" />
        <el-table-column label="消费时间" align="center" prop="createTime" width="100" />
        <el-table-column label="技师" align="center" prop="technicianName"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMember,
  getMember,
  delMember,
  addMember,
  updateMember,
  listMemberRegion,
  listMemberStore,
  listMemberRule,
  listMemberUser,
  getMemberContinue,
  addMemberContinueCard,
  fetchReference,
  listtechnicianList,
  listnormalList,
  getCardPerson,
  giveUserCoupon,
  getMemberInfo,
  getConsumptionCludes,
  chenData,
} from "@/api/system/card/memCard";
import {
  listcoupon,
  getZyCouponEffectiveList,
} from "@/api/system/coupon/couponList";
export default {
  name: "Store",
  data() {
    return {
      map: null,
      scanCode: "",
      local: null,
      mk: null,
      latitude: "",
      longitude: "",
      keyWords: "",
      result: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      jishi: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      //优惠券列表数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        regionName: null,
        storeName: null,
        userName: "",
        phoneNumber: null,
        userId: null,
        // createTime: null,
        // province: null,
        // provinceString: null,
        // city: null,
        // cityString: null,
        // county: null,
        // countyString: null,
        // detail: null,
        // longitude: null,
        // latitude: null,
        // intro: null,
        // images: null,
        // status: null,
        // dateOfBirth: null,
        // isInitiate: null,
        // openingTime: null,
        // closingTime: null,
        // gender: null,
      },
      pageNum: 1,
      pageSize: 10,
      total1: 0,
      // 表单参数
      form: {
        actuallyMoney: '',
      },
      // 表单校验
      rules: {
        actuallyMoney: [
          { required: true, message: "请输入实付金额", trigger: "blur" },
        ],
        phoneNumber: [
          { required: true, message: "请输入电话", trigger: "blur" },
        ],
        userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],

        ruleId: [{ required: true, message: "请选择会员卡", trigger: "blur" }],
        paymentType: [
          { required: true, message: "请选择支付方式", trigger: "blur" },
        ],
        payCode: [{ required: true, message: "请输入支付码", trigger: "blur" }],
      },
      options: [],
      List: [
        {
          key: 1,
          value: "营业中",
        },
        {
          key: 2,
          value: "未营业",
        },
      ],
      //性别
      gender: [
        {
          key: 0,
          value: "男",
        },
        {
          key: 1,
          value: "女",
        },
        {
          key: 2,
          value: "未知",
        },
      ],
      money: [
        // { key: 1, value: "微信" },
        // { key: 2, value: "支付宝" },
        { key: 3, value: "现金" },
        // { key: 4, value: "银行卡" },
        // { key: 5, value: "店铺储蓄卡" },

        { key: 7, value: "扫码支付" },
        { key: 6, value: "其他" },
        // { key: 8, value: "团购券" },
      ],
      moneyConfig: {
        1: { text: "微信" },
        2: { text: "支付宝" },
        3: { text: "现金" },
        4: { text: "银行卡" },
        5: { text: "店铺储蓄卡" },
        6: { text: "其他" },
        7: { text: "扫码支付" },
        8: { text: "团购券" },
        default: { text: "--" },
      },
      region: [],
      store: [],
      Rule: [],
      userName: [],
      //是否赠送优惠券弹框
      giveDialog: false,
      giveIds: [],
      disabled: false,
      isInput: false,
      isConsumCludes: false,
      consumCludes: [],
      isGroupBuy: false,
      userIds: [],
      memberDays: "",
      memberPrice: "",
    };
  },
  created() {
    this.getList();
    this.listMemberRegion();
    // this.listMemberRule();
    this.listMemberUser();
    listnormalList().then((res) => {
      this.jishi = res.data.map((rItem) => {
        return {
          key: rItem.id,
          value: rItem.name,
        };
      });
    });
    // listMemberStore().then((res) => {
    //   this.store = res.data.map((rItem) => {
    //     return {
    //       key: rItem.id,
    //       value: rItem.storeName,
    //     };
    //   });
    // });
  },
  watch: {
    "form.regionId": {
      handler(newValue, oldValue) {
        this.listMemberRegion();
        this.getListMemberStore(newValue);
      },
      // 开启 immediate 选项，组件创建时立即执行一次 handler
      immediate: true,
    },
    "form.storeId": {
      handler(newValue, oldValue) {
        // 当 formData.name 发生变化时，调用接口
        this.changeStore(newValue);
      },
      // 开启 immediate 选项，组件创建时立即执行一次 handler
      immediate: true,
    },
  },
  methods: {
    queryConsumptionList(item) {
      getConsumptionCludes({ id: item.id }).then((res) => {
        console.log(res);
        this.consumCludes = res.rows;
        this.isConsumCludes = true;
      });
    },
    //关闭付款弹窗
    closeCommonVisible() {
      this.form.payCode = "";
    },
    //支付方式变更
    paymentTypeChange(e) {
      console.log("支付方式-->", e);
      if (e == 7) {
        this.$nextTick(() => {
          this.$refs.barcode.focus();
        });
      }

      if (e == 8) {
        this.isGroupBuy = true;
      } else {
        this.isGroupBuy = false;
      }
    },
    //监听扫码枪
    handleScanCode(event) {
      console.log("回车事件--->", event);
      this.$modal.msgSuccess("扫码成功，请点击确认收款");
      this.form.payCode = event;
    },
    //点击赠送优惠券
    handleGive(row) {
      this.giveDialog = true;
      this.title = "赠送优惠券";
      this.id = row.id;
      this.getCouponList();
      1;
    },
    //优惠券列表
    getCouponList() {
      this.loading = true;
      const params = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        getPath: 3,
        state: 1,
      };
      getZyCouponEffectiveList(params).then((response) => {
        this.couponList = response.rows;
        this.total1 = response.total;
        this.loading = false;
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getCouponList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getCouponList();
    },
    //赠送优惠券
    couponSubmit() {
      if(this.giveIds==''){
        this.$modal.msgError('您没有选择任何优惠券');
        return false;
      }
      const params = {
        userIds: this.userIds,
        couponIds: this.giveIds,
      };
      giveUserCoupon(params).then((response) => {
        if (response.code == 200) {
          this.giveDialog = false;
          this.$message.success(response.msg);
          this.getCouponList();
          this.getList();
        }
      });
    },
    //取消赠送
    couponCancel() {
      this.giveDialog = false;
    },
    //赠送优惠券多选
    handleGiveChange(selection) {
      alert(selection.length);
      this.giveIds = selection.map((item) => item.id).join(",");
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    listMemberRegion() {
      listMemberRegion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
        console.log(this.region, 'this.region')
      });
    },
    // listMemberRule() {
    //   listMemberRule().then((res) => {
    //     this.Rule = res.rows.map((rItem) => {
    //       return {
    //         key: rItem.id,
    //         value: rItem.ruleName,
    //         price: rItem.price,
    //         days: rItem.days,
    //       };
    //     });
    //   });
    // },
    listMemberUser() {
      listMemberUser().then((res) => {
        this.userName = res.rows.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.phoneNumber,
            userName: rItem.userName,
            sex: rItem.sex,
            birthday: rItem.birthday,
          };
        });
      });
    },
    listMemberStore() {
      listMemberStore().then((res) => {
        this.listMemberStore = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    phoneNumberBlur() {
      const params = {
        phoneNumber: this.form.phoneNumber,
      };
      getCardPerson(params).then((res) => {
        if (res.code !== 200) return;
        this.form = {
          ...this.form,
          userId: res.rows[0].userId,
          userName: res.rows[0].userName,
        };
      });
    },
    getListMemberStore(regionId) {
      listMemberStore({ regionId }).then((res) => {
        this.store = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          };
        });
      });
    },
    getListMemberRule(regionId) {
      listMemberRule({ regionId, status: 1 }).then((res) => {
        console.log('1111111', res.rows)
        this.Rule = res.rows.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.ruleName,
            price: rItem.price,
            days: rItem.days,
            discountRate: rItem.discountRate,
          };
        });
        // if (this.form.ruleId) {
        //   const selectedOption = this.Rule.find((item) => item.key === this.form.ruleId);
        //   this.memberDays = selectedOption.days;
        //   this.memberPrice = selectedOption.price;
        //   this.form.actuallyMoney = selectedOption.price
        // }
      });
    },
    changeRegion(value) {
      const selectedOption = this.region.find((item) => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      this.form.regionName = selectedValue;
      this.form.storeId = "";
      this.form.ruleId = "";
      this.getListMemberStore(value);
      this.getListMemberRule(value);
    },
    changeStore(value) {
      const selectedOption = this.store.find((item) => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      this.form.storeName = selectedValue;
      // this.form.referrerId = "";
      listnormalList({ belongStoreId: value }).then((res) => {
        this.jishi = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.name,
          };
        });
      });
    },
    changephoneNumber(value) {
      console.log(this.userName, "4444");
      if (!this.form.storeId) {
        this.$message.error("请选择门店");
        this.form.phoneNumber = "";
        return;
      }
      const selectedOption = this.userName.find((item) => item.key === value);
      console.log(selectedOption, "122");
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      const selecteduserName = selectedOption.userName;

      this.form.phoneNumber = selectedValue;
      this.form.gender = selectedOption.sex;
      this.form.dateOfBirth = selectedOption.birthday;
      this.getNumberInfo();

      // if(selectedOption===0){
      //   this.form.userId=value
      // }
      this.form.userName = selecteduserName;
    },
    getNumberInfo() {
      chenData({
        phoneNumber: this.form.phoneNumber,
        storeId: this.form.storeId,
      }).then((res) => {
        console.log("res", res);
      });
    },
    blurphoneNumber() {
      console.log(this.form.userId, 9988);
      // this.form.userId=value
    },
    changeuserName(value) {
      const selectedOption = this.userName.find((item) => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      const selectedphoneNumber = selectedOption.phoneNumber;
      this.form.phoneNumber = selectedphoneNumber;
      this.form.userName = selectedValue;
    },
    changeReferrer(value) {
      const selectedOption = this.jishi.find((item) => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      this.form.referrerId = selectedKey;
      this.form.referrerName = selectedValue;
    },
    changeRule(value, type) {
      //新卡
      const selectedOption = this.Rule.find((item) => item.key === value);
      console.log(selectedOption, 444);
      this.memberDays = selectedOption.days;
      this.memberPrice = selectedOption.price;

      //原卡
      const selectedOptionOld = this.Rule.find(
        (item) => item.value === this.form.originRuleName
      );
      console.log(selectedOptionOld, 555);

      this.form.discountRate = selectedOption.discountRate;
      this.form.actuallyMoney = selectedOption.price; //卡实付金额

      if (selectedOptionOld) {

        this.form.dayDiscountPrice = (
          (selectedOptionOld.price * this.form.validDays).toFixed(2) /
          selectedOptionOld.days
        ).toFixed(2); //旧卡折扣金额

        this.form.price = (selectedOption.price - this.form.dayDiscountPrice).toFixed(2);//新卡实付金额
      }

      // this.form.price = selectedPrice;
      // this.form.days = selectedDays;

      // console.log(this.Rule, "Rule");

      // console.log(this.form.price, "price");
      // if (this.title == "会员卡续卡") {
      //   this.Rule.forEach((element) => {
      //     if (element.price < this.form.price) {
      //       element.disabled = true;
      //     }
      //   });
      // }

      if (!type) {
        // this.form.validDays = selectedDays
      }

      // 查询当前电话会员是否有该会员卡，计算天数；
      //  alert(value);

      // const params = {
      //   ruleId: value,
      //   phoneNumber: this.form.phoneNumber,
      // };
      // this.form.orgPrice = selectedPrice;
      // getMemberInfo(params).then((response) => {
      //   if (response.code == 200) {
      //     //this.giveDialog = false;
      //     if (response.data == null) {
      //       this.form.dayDiscountPrice = 0;
      //       this.form.price = selectedPrice;
      //     } else {
      //       // this.form.dayDiscountPrice=  (parseFloat(parseFloat(selectedPrice)*(response.data.validDays))/parseFloat(selectedDays)).toFixed(2);
      //       this.form.dayDiscountPrice = (
      //         (selectedPrice * response.data.validDays).toFixed(2) /
      //         selectedDays
      //       ).toFixed(2);
      //       this.isInput = !this.isInput;
      //       this.form.price = (
      //         selectedPrice - this.form.dayDiscountPrice
      //       ).toFixed(2);
      //     }
      //   }
      // });

      // this.form.orgPrice = selectedPrice
      // this.form.dayDiscountPrice =


    },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      listMember(this.queryParams).then((response) => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        payCode: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        ruleId: null,
        intro: null,
        images: null,
        dayDiscountPrice: null,
        dateOfBirth: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        createTime: null,
        updateTime: null,
        gender: null,
        validDays: null,
        originRuleName: null,
        groupPurchaseMoney: null,
        groupPurchaseId: null,
        referrerId: null,
        actuallyMoney: ''
      };
      this.isGroupBuy = false;
      this.jishi = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        regionName: null,
        storeName: null,
        userName: "",
        phoneNumber: null,
        userId: null,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection, "selection0");
      this.ids = selection.map((item) => item.id).join(",");
      this.userIds = selection.map((item) => item.userId).join(",");
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      // this.listMemberRule();
      this.store = [];
      this.Rule = [];
      this.listMemberUser();
      this.title = "添加会员卡";
      this.memberDays = "",
        this.memberPrice = "",
        this.disabled = false;
    },
    // 上下架
    handleGround(row, cardStatus) {
      const params = {
        id: row.id,
        cardStatus: cardStatus,
        userId: row.userId,
        userName: row.userName,
      };
      this.$confirm(
        `此操作将${cardStatus === 1 ? "启用" : "禁用"}该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          updateMember(params).then((res) => {
            this.$message({
              type: "success",
              message: `${cardStatus === 1 ? "启用" : "禁用"}成功!`,
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getMember(id).then((response) => {
        this.form = response.data;
        console.log(this.form, 'this.form');

        this.open = true;
        this.title = "修改会员卡";
        this.disabled = true;
        if (response.data.paymentType == 8) {
          this.isGroupBuy = true;
        }
        this.getListMemberStore(this.form.regionId);
        this.getListMemberRule(this.form.regionId);
        // this.changeRegion(response.data.regionId);
      });
    },
    handleRenew(row) {
      this.reset();
      const id = row.id || this.ids;
      getMemberContinue(id).then((response) => {
        response.data.paymentType = ''
        this.form = response.data;
        this.form.originRuleName = response.data.ruleName;
        this.open = true;
        this.title = "会员卡续卡";
        this.disabled = false;
        listnormalList({ belongStoreId: response.data.storeId }).then((res) => {
          this.jishi = res.data.map((rItem) => {
            return {
              key: rItem.id,
              value: rItem.name,
            };
          });
        });
        listMemberRule({ regionId: response.data.regionId }).then((res) => {
          this.Rule = res.rows.map((rItem) => {
            return {
              key: rItem.id,
              value: rItem.ruleName,
              price: rItem.price,
              days: rItem.days,
              disabled: Number(this.form.buyMoney) > Number(rItem.price),
            };
          });
          // console.log("this.Rule1455", this.form.buyMoney, this.Rule);
          this.changeRule(this.form.ruleId, 1);
        });
        if (this.form.paymentType == 8) {
          this.isGroupBuy = true;
        }
        ///
      });
    },

    //////////////////////

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.title == "修改会员卡") {
            updateMember(this.form).then((response) => {
              this.form.payCode = "";
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.$nextTick(() => {
                  this.$refs.code.focus();
                });
              }
            });
          } else if (this.title == "会员卡续卡") {
            addMemberContinueCard(this.form).then((response) => {
              this.form.payCode = "";
              if (response.code == 200) {
                this.$modal.msgSuccess("续费成功");
                this.open = false;
                this.getList();
              } else {
                this.$nextTick(() => {
                  this.$refs.code.focus();
                });
              }
            });
          } else {
            this.form.cardStatus = 1;
            this.form.price = this.form.actuallyMoney;
            console.log("this.form", this.form);

            addMember(this.form).then((response) => {
              this.form.payCode = "";
              if (response.code == 200) {
                this.$modal.msgSuccess("新建成功");
                this.open = false;
                this.getList();
              } else {
                this.$nextTick(() => {
                  this.$refs.code.focus();
                });
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认会员卡编号为"' + ids + '"的数据项？')
        .then(function () {
          return delMember(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/system/member/export",
        {
          ...this.queryParams,
        },
        `memCard_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style>
.dialog-footer {
  text-align: center;
}

.descStyle {
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.tooltip {
  max-width: 650px;
}
</style>
